import numpy as np
import scipy.optimize as op
def fun(x):
    return x[0]**2 + x[1]**2 + x[2]**2 + 8

def con1(x):
    return x[0]**2 - x[1] + x[2]**2

def con2(x):
    return 20 - x[0] - x[1]**2 - x[2]**2

def con3(x):
    return -x[0] - x[1]**2 + 2

def con4(x):
    return x[1] + 2*x[2]**2 - 3

x = np.zeros(3)
bound = (0,None)
bounds = (bound,bound,bound)
cons1 = {'type':'ineq','fun':con1}
cons2 = {'type':'ineq','fun':con2}
cons3 = {'type':'eq','fun':con3}
cons4 = {'type':'eq','fun':con4}
cons = [cons1,cons2,cons3,cons4]
prob = op.minimize(fun,x,method='SLSQP',bounds=bounds,constraints=cons)
x = prob.x
print("最优值为：",fun(x))
print("最优解为：\n",x[0],x[1],x[2])

def fun2(x):
    return 2*x[0]**2 - 4*x[0]*x[1] + 4*x[1]**2 - 6*x[0] - 3*x[1]

def con5(x):
    return -x[0] - x[1] + 3

def con6(x):
    return 9 - 4*x[0] - x[1]

x2 = np.zeros(2)
bound1 = (0,None)
bounds1 = (bound1,bound1)
cons5 = {'type':'ineq','fun':con5}
cons6 = {'type':'ineq','fun':con6}
conss = [cons5,cons6]
prob2 = op.minimize(fun2,x2,method='SLSQP',bounds=bounds1,constraints=conss)
x2 = prob2.x
print("最优值为：",fun2(x2))
print("最优解为：\n",x2[0],x2[1])